package zqservlet;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.hikvision.artemis.sdk.ArtemisHttpUtil;
import com.hikvision.artemis.sdk.config.ArtemisConfig;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import zqdb.O_INFO;
import zqtools.DBUtil;

import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

@WebServlet("/hik")
public class hikServlet extends HttpServlet {
    static {
        ArtemisConfig.host = "10.7.60.45:443";// 代理API网关nginx服务器ip端口
        ArtemisConfig.appKey = "25415289";// 秘钥appkey
        ArtemisConfig.appSecret = "XE2ajSWkBS0FFcuwQeuE";// 秘钥appSecret
    }

    private static final String ARTEMIS_PATH = "/artemis";

    @Override
    public void service(ServletRequest request, ServletResponse response) throws ServletException, IOException {
        final String VechicleDataApi0 = ARTEMIS_PATH + "/api/resource/v1/person/personId/personInfo";
        final String VechicleDataApi1 = ARTEMIS_PATH + "/api/resource/v1/person/single/add";
        final String VechicleDataApi2 = ARTEMIS_PATH + "/api/cis/v1/card/bindings";
        final String VechicleDataApiSingleUpdate = ARTEMIS_PATH + "/api/resource/v1/person/single/update";
        final String VechicleDataApiFaceSingleAdd = ARTEMIS_PATH + "/api/resource/v1/face/single/add";
        final String VechicleDataApiFaceSingleDelete = ARTEMIS_PATH + "/api/resource/v1/face/single/delete";

        Map<String, String> path1 = new HashMap<String, String>(2) {
            {
                put("https://", VechicleDataApi1);
            }
        };

        Map<String, String> path2 = new HashMap<String, String>(2) {
            {
                put("https://", VechicleDataApi2);
            }
        };
        Map<String, String> path0 = new HashMap<String, String>(2) {
            {
                put("https://", VechicleDataApi0);
            }
        };
        Map<String, String> pathSingleUpdate = new HashMap<String, String>(2) {
            {
                put("https://", VechicleDataApiSingleUpdate);
            }
        };
        Map<String, String> pathFaceSingleAdd = new HashMap<String, String>(2) {
            {
                put("https://", VechicleDataApiFaceSingleAdd);
            }
        };
        Map<String, String> pathFaceSingleDelete = new HashMap<String, String>(2) {
            {
                put("https://", VechicleDataApiFaceSingleDelete);
            }
        };

        JSONObject jsonBody0 = new JSONObject();
        jsonBody0.put("personId", request.getParameter("personId"));
        String body0 = jsonBody0.toJSONString();
        HttpResponse result0 = ArtemisHttpUtil.doPostStringImgArtemis(path0, body0, null, null, "application/json", null);
        try {
            if (200 == result0.getStatusLine().getStatusCode()) {
                HttpEntity entity0 = result0.getEntity();
                InputStream in0 = entity0.getContent();
                StringBuilder sb0 = new StringBuilder();
                byte[] b0 = new byte[1024];
                int len;
                while ((len = in0.read(b0)) != -1) {
                    sb0.append(new String(b0, 0, len));
                }
                in0.close();

                JSONObject jsonObject0 = JSONObject.parseObject(sb0.toString());
                JSONObject jsub0 = jsonObject0.getJSONObject("data");

                if (jsub0 == null) {
                    ///////////------download and bingdcard
                    JSONObject jsonBody1 = new JSONObject();
                    String ls_rykh = request.getParameter("cardno");
                    String ls_personid = request.getParameter("personId");
                    String ls_orgindex = request.getParameter("orgIndexCode");

                    jsonBody1.put("personId", ls_personid);
                    jsonBody1.put("personName", request.getParameter("personName"));
                    jsonBody1.put("gender", request.getParameter("gender"));
                    jsonBody1.put("orgIndexCode", ls_orgindex);
                    jsonBody1.put("phoneNo", request.getParameter("phoneNo"));
                    jsonBody1.put("certificateType", "111");
                    jsonBody1.put("certificateNo", request.getParameter("certificateNo"));
                    jsonBody1.put("jobNo", request.getParameter("jobNo"));

                    com.alibaba.fastjson.JSONObject jRet = new com.alibaba.fastjson.JSONObject();
                    String body1 = jsonBody1.toJSONString();
                    //System.out.println(body1);
                    HttpResponse result1 = ArtemisHttpUtil.doPostStringImgArtemis(path1, body1, null, null, "application/json", null);
                    try {
                        if (200 == result1.getStatusLine().getStatusCode()) {
                            HttpEntity entity1 = result1.getEntity();
                            InputStream in1 = entity1.getContent();
                            StringBuilder sb1 = new StringBuilder();
                            byte[] b1 = new byte[1024];
                            while ((len = in1.read(b1)) != -1) {
                                sb1.append(new String(b1, 0, len));
                            }
                            in1.close();
                            JSONObject jsonObject1 = JSONObject.parseObject(sb1.toString());
                            //System.out.println("----------------------   " + jsonObject1);
                            if ("0".equals(jsonObject1.get("code")) && "success".equals(jsonObject1.get("msg"))) {
                                jRet.put("code", "0");
                                jRet.put("msg", "success");
                                ////////////////////////////////////////////////////////////////////////////////
                                JSONObject jsonBody2 = new JSONObject();
                                JSONObject jsonsub2 = new JSONObject();
                                JSONArray jarr2 = new JSONArray();
                                jsonBody2.put("startDate", "2022-07-01");
                                jsonBody2.put("endDate", "2037-12-31");

                                jsonsub2.put("cardNo", ls_rykh);
                                jsonsub2.put("personId", ls_personid);
                                jsonsub2.put("orgIndexCode", ls_orgindex);
                                jsonsub2.put("cardType", "1");
                                jarr2.add(jsonsub2);

                                jsonBody2.put("cardList", jarr2);

                                com.alibaba.fastjson.JSONObject jRet2 = new com.alibaba.fastjson.JSONObject();
                                String body2 = jsonBody2.toJSONString();
                                HttpResponse result2 = ArtemisHttpUtil.doPostStringImgArtemis(path2, body2, null, null, "application/json", null);
                                try {
                                    if (200 == result2.getStatusLine().getStatusCode()) {
                                        HttpEntity entity2 = result2.getEntity();
                                        InputStream in2 = entity2.getContent();
                                        StringBuilder sb2 = new StringBuilder();
                                        byte[] b2 = new byte[1024];
                                        int len2;
                                        while ((len2 = in2.read(b2)) != -1) {
                                            sb2.append(new String(b2, 0, len2));
                                        }
                                        in2.close();
                                        JSONObject jsonObject2 = JSONObject.parseObject(sb2.toString());
                                    }
                                } catch (Exception e) {
                                    jRet2.put("code", "1");
                                    jRet2.put("msg", "与海康通讯出错...");
                                }
                                ////////////////////////////////////////////////////////////////////////////////////////
                                ////////////////////////////////////////////////////////////////////////////////
                                if (request.getParameter("faceData").length() > 0) {
                                    JSONObject jsonBody3 = new JSONObject();
                                    jsonBody3.put("faceId", request.getParameter("faceid"));
                                    String body3 = jsonBody3.toJSONString();
                                    try
                                    {
                                        ArtemisHttpUtil.doPostStringImgArtemis(pathFaceSingleDelete, body3, null, null, "application/json", null);
                                    }finally {
                                        JSONObject jsonBody4 = new JSONObject();
                                        jsonBody4.put("faceData", request.getParameter("faceData"));
                                        jsonBody4.put("personId", ls_personid);

                                        com.alibaba.fastjson.JSONObject jRet3 = new com.alibaba.fastjson.JSONObject();
                                        String body4 = jsonBody4.toJSONString();
                                        HttpResponse result4 = ArtemisHttpUtil.doPostStringImgArtemis(pathFaceSingleAdd, body4, null, null, "application/json", null);
                                        try {
                                            if (200 == result4.getStatusLine().getStatusCode()) {
                                                HttpEntity entity3 = result4.getEntity();
                                                InputStream in3 = entity3.getContent();
                                                StringBuilder sb3 = new StringBuilder();
                                                byte[] b3 = new byte[1024];
                                                while ((len = in3.read(b3)) != -1) {
                                                    sb3.append(new String(b3, 0, len));
                                                }
                                                in3.close();
                                                JSONObject jsonObject3 = JSONObject.parseObject(sb3.toString());
                                                O_INFO of = new O_INFO();
                                                of.setCMD("CD");
                                                of.setVALUE01(jsonObject3.getJSONObject("data").getString("personId"));
                                                of.setVALUE02(jsonObject3.getJSONObject("data").getString("faceId"));
                                                DBUtil.f_query2(of);
                                                //System.out.println(jsonObject3);
                                            }
                                        } catch (Exception e) {
                                            jRet3.put("code", "1");
                                            jRet3.put("msg", "与海康通讯出错...");
                                        }
                                    }
                                }
                                ////////////////////////////////////////////////////////////////////////////////////////
                            } else {
                                jRet.put("code", "1");
                                if ("PersonId Already In Db".equals(jsonObject1.get("msg"))) {
                                    jRet.put("msg", "海康平台已有该人员的信息...");
                                } else if ("PersonFace Exists".equals(jsonObject1.get("msg"))) {
                                    jRet.put("msg", "海康平台已有相同照片ID。</br>请在海康已删除人员中彻底进行彻底删除...");
                                } else if ("Unqiue Field[certificateNo] Already Exists".equals(jsonObject1.get("msg"))) {
                                    jRet.put("msg", "海康平台已有相同身份证号码...");
                                } else {
                                    jRet.put("msg", jsonObject1.get("msg"));
                                }
                            }
                        } else {
                            jRet.put("code", "1");
                            jRet.put("msg", "与海康通讯出错...");
                        }
                    } catch (Exception e) {
                        jRet.put("code", "1");
                        jRet.put("msg", "与海康通讯出错...");
                    }

                    response.setContentType("text/html;charset=utf-8");
                    response.getWriter().print(jRet);
                }
                else
                {
                    /////////-----UPDATE
                    JSONObject jsonBody1 = new JSONObject();
                    String ls_rykh = request.getParameter("cardno");
                    String ls_personid = request.getParameter("personId");
                    String ls_orgindex = request.getParameter("orgIndexCode");

                    jsonBody1.put("personId", ls_personid);
                    jsonBody1.put("personName", request.getParameter("personName"));
                    jsonBody1.put("gender", request.getParameter("gender"));
                    jsonBody1.put("orgIndexCode", ls_orgindex);
                    jsonBody1.put("phoneNo", request.getParameter("phoneNo"));
                    jsonBody1.put("certificateType", "111");
                    jsonBody1.put("certificateNo", request.getParameter("certificateNo"));
                    jsonBody1.put("jobNo", request.getParameter("jobNo"));

                    com.alibaba.fastjson.JSONObject jRet = new com.alibaba.fastjson.JSONObject();
                    String body1 = jsonBody1.toJSONString();
                    HttpResponse result1 = ArtemisHttpUtil.doPostStringImgArtemis(pathSingleUpdate, body1, null, null, "application/json", null);
                    try {
                        if (200 == result1.getStatusLine().getStatusCode()) {
                            HttpEntity entity1 = result1.getEntity();
                            InputStream in1 = entity1.getContent();
                            StringBuilder sb1 = new StringBuilder();
                            byte[] b1 = new byte[1024];
                            while ((len = in1.read(b1)) != -1) {
                                sb1.append(new String(b1, 0, len));
                            }
                            in1.close();
                            JSONObject jsonObject1 = JSONObject.parseObject(sb1.toString());
                            if ("0".equals(jsonObject1.get("code")) && "success".equals(jsonObject1.get("msg"))) {
                                jRet.put("code", "0");
                                jRet.put("msg", "success");
                                ////////////////////////////////////////////////////////////////////////////////
                                JSONObject jsonBody2 = new JSONObject();
                                JSONObject jsonsub2 = new JSONObject();
                                JSONArray jarr2 = new JSONArray();
                                jsonBody2.put("startDate", "2022-07-01");
                                jsonBody2.put("endDate", "2037-12-31");

                                jsonsub2.put("cardNo", ls_rykh);
                                jsonsub2.put("personId", ls_personid);
                                jsonsub2.put("orgIndexCode", ls_orgindex);
                                jsonsub2.put("cardType", "1");
                                jarr2.add(jsonsub2);

                                jsonBody2.put("cardList", jarr2);

                                com.alibaba.fastjson.JSONObject jRet2 = new com.alibaba.fastjson.JSONObject();
                                String body2 = jsonBody2.toJSONString();
                                HttpResponse result2 = ArtemisHttpUtil.doPostStringImgArtemis(path2, body2, null, null, "application/json", null);
                                try {
                                    if (200 == result2.getStatusLine().getStatusCode()) {
                                        HttpEntity entity2 = result2.getEntity();
                                        InputStream in2 = entity2.getContent();
                                        StringBuilder sb2 = new StringBuilder();
                                        byte[] b2 = new byte[1024];
                                        int len2;
                                        while ((len2 = in2.read(b2)) != -1) {
                                            sb2.append(new String(b2, 0, len2));
                                        }
                                        in2.close();
                                        JSONObject jsonObject2 = JSONObject.parseObject(sb2.toString());
                                        //System.out.println(jsonObject2);
                                    }
                                } catch (Exception e) {
                                    jRet2.put("code", "1");
                                    jRet2.put("msg", "与海康通讯出错...");
                                }
                                ////////////////////////////////////////////////////////////////////////////////////////
                                ////////////////////////////////////////////////////////////////////////////////
                                if (request.getParameter("faceData").length() > 0) {
                                    JSONObject jsonBody3 = new JSONObject();
                                    jsonBody3.put("faceId", request.getParameter("faceid"));
                                    String body3 = jsonBody3.toJSONString();
                                    try
                                    {
                                        ArtemisHttpUtil.doPostStringImgArtemis(pathFaceSingleDelete, body3, null, null, "application/json", null);
                                    }finally {
                                        JSONObject jsonBody4 = new JSONObject();
                                        jsonBody4.put("faceData", request.getParameter("faceData"));
                                        jsonBody4.put("personId", ls_personid);

                                        com.alibaba.fastjson.JSONObject jRet3 = new com.alibaba.fastjson.JSONObject();
                                        String body4 = jsonBody4.toJSONString();
                                        HttpResponse result4 = ArtemisHttpUtil.doPostStringImgArtemis(pathFaceSingleAdd, body4, null, null, "application/json", null);
                                        try {
                                            if (200 == result4.getStatusLine().getStatusCode()) {
                                                HttpEntity entity3 = result4.getEntity();
                                                InputStream in3 = entity3.getContent();
                                                StringBuilder sb3 = new StringBuilder();
                                                byte[] b3 = new byte[1024];
                                                while ((len = in3.read(b3)) != -1) {
                                                    sb3.append(new String(b3, 0, len));
                                                }
                                                in3.close();
                                                JSONObject jsonObject3 = JSONObject.parseObject(sb3.toString());
                                                O_INFO of = new O_INFO();
                                                of.setCMD("CD");
                                                of.setVALUE01(jsonObject3.getJSONObject("data").getString("personId"));
                                                of.setVALUE02(jsonObject3.getJSONObject("data").getString("faceId"));
                                                DBUtil.f_query2(of);
                                            }
                                        } catch (Exception e) {
                                            jRet3.put("code", "1");
                                            jRet3.put("msg", "与海康通讯出错...");
                                        }
                                    }
                                }
                                ////////////////////////////////////////////////////////////////////////////////////////
                            } else {
                                jRet.put("code", "1");
                                if ("PersonId Already In Db".equals(jsonObject1.get("msg"))) {
                                    jRet.put("msg", "海康平台已有该人员的信息...");
                                } else if ("PersonFace Exists".equals(jsonObject1.get("msg"))) {
                                    jRet.put("msg", "海康平台已有相同照片ID。</br>请在海康已删除人员中彻底进行彻底删除...");
                                } else if ("Unqiue Field[certificateNo] Already Exists".equals(jsonObject1.get("msg"))) {
                                    jRet.put("msg", "海康平台已有相同身份证号码...");
                                } else {
                                    jRet.put("msg", jsonObject1.get("msg"));
                                }
                            }
                        } else {
                            jRet.put("code", "1");
                            jRet.put("msg", "与海康通讯出错...");
                        }
                    } catch (Exception e) {
                        jRet.put("code", "1");
                        jRet.put("msg", "与海康通讯出错...");
                    }

                    response.setContentType("text/html;charset=utf-8");
                    response.getWriter().print(jRet);
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }


//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//        final String VechicleDataApi = ARTEMIS_PATH +"/api/resource/v1/person/single/add";
//        final String VechicleDataApi2 = ARTEMIS_PATH +"/api/cis/v1/card/bindings";
//
//        Map<String,String> path = new HashMap<String,String>(2){
//            {
//                put("https://",VechicleDataApi);
//            }
//        };
//
//        Map<String,String> path2 = new HashMap<String,String>(2){
//            {
//                put("https://",VechicleDataApi2);
//            }
//        };
//
//        JSONObject jsonBody = new JSONObject();
//        String ls_rykh = request.getParameter("cardno");
//        String ls_personid = request.getParameter("personId");
//        String ls_orgindex = request.getParameter("orgIndexCode");
//        jsonBody.put("personId", ls_personid);
//        jsonBody.put("personName", request.getParameter("personName"));
//        jsonBody.put("gender", request.getParameter("gender"));
//        jsonBody.put("orgIndexCode", ls_orgindex);
//        jsonBody.put("phoneNo", request.getParameter("phoneNo"));
//        jsonBody.put("certificateType", "111");
//        jsonBody.put("certificateNo", request.getParameter("certificateNo"));
//        jsonBody.put("jobNo", request.getParameter("jobNo"));
//
//        if (request.getParameter("faceData").length() > 0){
//            JSONObject jface = new JSONObject();
//            jface.put("faceData", request.getParameter("faceData"));
//            JSONArray jfaceArr = new JSONArray();
//            jfaceArr.add(jface);
//            jsonBody.put("faces", jfaceArr);
//        }
//
//        com.alibaba.fastjson.JSONObject jRet = new com.alibaba.fastjson.JSONObject();
//        String body = jsonBody.toJSONString();
//        HttpResponse result = ArtemisHttpUtil.doPostStringImgArtemis(path,body,null,null,"application/json",null);
//        try {
//            if (200== result.getStatusLine().getStatusCode()) {
//                HttpEntity entity = result.getEntity();
//                InputStream in = entity.getContent();
//                StringBuilder sb = new StringBuilder();
//                byte[] b = new byte[1024];
//                int len;
//                while ((len = in.read(b)) != -1) {
//                    sb.append(new String(b, 0, len));
//                }
//                in.close();
//                JSONObject jsonObject = JSONObject.parseObject(sb.toString());
//                if ("0".equals(jsonObject.get("code")) && "success".equals(jsonObject.get("msg")))
//                {
//                    jRet.put("code", "0");
//                    jRet.put("msg", "success");
//                    ////////////////////////////////////////////////////////////////////////////////
//                    JSONObject jsonBody2 = new JSONObject();
//                    JSONObject jsonsub2 = new JSONObject();
//                    JSONArray jarr2 = new JSONArray();
//                    jsonBody2.put("startDate", "2022-07-01");
//                    jsonBody2.put("endDate", "2037-12-31");
//
//                    jsonsub2.put("cardNo", ls_rykh);
//                    jsonsub2.put("personId", ls_personid);
//                    jsonsub2.put("orgIndexCode", ls_orgindex);
//                    jsonsub2.put("cardType", "1");
//                    jarr2.add(jsonsub2);
//
//                    jsonBody2.put("cardList", jarr2);
//
//                    com.alibaba.fastjson.JSONObject jRet2 = new com.alibaba.fastjson.JSONObject();
//                    String body2 = jsonBody2.toJSONString();
//                    HttpResponse result2 = ArtemisHttpUtil.doPostStringImgArtemis(path2,body2,null,null,"application/json",null);
//                    try {
//                        if (200== result2.getStatusLine().getStatusCode()) {
//                            HttpEntity entity2 = result2.getEntity();
//                            InputStream in2 = entity2.getContent();
//                            StringBuilder sb2 = new StringBuilder();
//                            byte[] b2 = new byte[1024];
//                            int len2;
//                            while ((len2 = in2.read(b2)) != -1) {
//                                sb2.append(new String(b2, 0, len2));
//                            }
//                            in2.close();
//                            JSONObject jsonObject2 = JSONObject.parseObject(sb2.toString());
//                            System.out.println(jsonObject2);
//                        }
//                    } catch (Exception e) {
//                        jRet2.put("code", "1");
//                        jRet2.put("msg", "与海康通讯出错...");
//                    }
//                    ////////////////////////////////////////////////////////////////////////////////////////
//                }
//                else {
//                    jRet.put("code", "1");
//                    if ("PersonId Already In Db".equals(jsonObject.get("msg")))
//                    {
//                        jRet.put("msg", "海康平台已有该人员的信息...");
//                    }
//                    else if ("PersonFace Exists".equals(jsonObject.get("msg")))
//                    {
//                        jRet.put("msg", "海康平台已有相同照片ID。</br>请在海康已删除人员中彻底进行彻底删除...");
//                    }
//                    else if ("Unqiue Field[certificateNo] Already Exists".equals(jsonObject.get("msg"))){
//                        jRet.put("msg", "海康平台已有相同身份证号码...");
//                    }
//
//                    else {
//                        jRet.put("msg", jsonObject.get("msg"));
//                    }
//                }
//            }else{
//                jRet.put("code", "1");
//                jRet.put("msg", "与海康通讯出错...");
//            }
//        } catch (Exception e) {
//            jRet.put("code", "1");
//            jRet.put("msg", "与海康通讯出错...");
//        }
//
//        response.setContentType("text/html;charset=utf-8");
//        response.getWriter().print(jRet);
    }

    public synchronized static void callPostImgStringApi(String a_personid) {
        final String VechicleDataApi = ARTEMIS_PATH + "/api/resource/v1/person/personId/personInfo";
        Map<String, String> path = new HashMap<String, String>(2) {
            {
                put("https://", VechicleDataApi);
            }
        };

        JSONObject jsonBody = new JSONObject();
        //jsonBody.put("personId", "f6da43792d2d4a1290d24a81b6ac1e9b");
        jsonBody.put("personId", a_personid);
        String body = jsonBody.toJSONString();
        //System.out.println("body: "+body);
        HttpResponse result = ArtemisHttpUtil.doPostStringImgArtemis(path, body, null, null, "application/json", null);
        try {
            HttpResponse resp = result;
            if (200 == resp.getStatusLine().getStatusCode()) {
                HttpEntity entity = resp.getEntity();
                InputStream in = entity.getContent();
                StringBuilder sb = new StringBuilder();
                byte[] b = new byte[1024];
                int len;
                while ((len = in.read(b)) != -1) {
                    sb.append(new String(b, 0, len));
                }
                in.close();

                JSONObject jsonObject = JSONObject.parseObject(sb.toString());
                JSONObject jsub = jsonObject.getJSONObject("data");
                if (jsub == null) {
                    System.out.println("没有相关人员的数据");
                } else {
                    System.out.println(jsub.get("personName"));
                }
            } else {
                System.out.println("下载出错");
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
